<template>
  <div class="agent-tree notice-tree">
    <div class="prompt">{{$t('configLazyLoad.noticeConfig.tip1')}}</div>
      <el-tree-new
        class="el-tree1"
        ref="tree"
        height="300"
        node-key="_id"
        :data="optionData"
        accordion
        default-expand-all
        :render-content="renderContent"
        :filter-node-method="filterNode">
      </el-tree-new>
  </div>

</template>
<script>
  import tree from '@/components/ui-modules/tree/src/tree.vue'
  import { deepClone } from '@/utils/m7Utils'
  export default {
    name: 'agentTree',
    data () {
      return {
        objSeat: {},
        inputValue: '',
        optionData: [],
        checkedAgents: []
      }
    },
    components: {
      'el-tree-new': tree
    },
    props: {
      readSeat: Object,
      random: Number
    },
    watch: {
      random () {
        this.objSeat = deepClone(this.readSeat)
        this.objSeat.showScope.ownerdep ? this.objSeat.showScope.ownerdep = this.objSeat.showScope.ownerdep.split(',') : this.objSeat.showScope.ownerdep = []
        this.objSeat.showScope.user ? this.objSeat.showScope.user = this.objSeat.showScope.user.split(',') : this.objSeat.showScope.user = []
        if (this.objSeat.showScope.ownercom === 'all') {
          this.handleData()
        } else {
          this.handleData1()
        }
      }
    },
    methods: {
      renderContent (h, { node, data, store }) {
        let agentFlag = false
        if ((node.childNodes.length) === 0 && (node.isLeaf === true)) {
          agentFlag = true
        }
        if (this.objSeat.readers.indexOf(data._id) > -1) {
          return (
            h('span', {
              class: {
                myheader: true,
                floatfl: agentFlag
              }
            }, [
              h('span', {
                domProps: {
                  innerHTML: data.label
                }
              }, [
              ]),
              h('span', {
                domProps: {
                  innerHTML: this.$t('configLazyLoad.noticeConfig.read')
                },
                style: {
                  color: '#459ae9'
                },
                class: {
                  readed: true
                }
              }, [
              ])
            ])
          )
        } else {
          return (
            h('span', {
              class: {
                myheader: true,
                floatfl: agentFlag
              }
            }, [
              h('span', {
                class: {
                  name: true
                },
                domProps: {
                  innerHTML: data.label
                }
              }, [
              ])
            ])
          )
        }
      },
      setDeptAgentCount (obj) {
        if (!obj.children && obj.type === 'agent') {
          return 1
        }

        let count = 0
        for (let i = 0; i < obj.children.length; i++) {
          count += this.setDeptAgentCount(obj.children[i])
        }
        obj.count = count
        obj.label = `${obj.label} (${count})`
        return count
      },
      resetAgent1 () {
        this.resetAgent()
      },
      deleteAgent1: function (_id) {
        this.deleteAgent(_id)
      },
      resetAgent () {
        this.$refs.tree.setCheckedKeys([])
      },
      deleteAgent (key) {
        this.$refs.tree.setChecked(key, false)
      },
      setCheckedAgent (ids) {
        console.log(this.checkedAgents)
        Promise.resolve(this.resetAgent()).then(() => {
          this.$refs.tree.setCheckedKeys(ids)
        })
      },
      filterNode (value, data) {
        if (!value) return true
        return data.type === 'agent' && (data.label.indexOf(value) !== -1 || data.pinyin.indexOf(value) !== -1)
      },
      handleData () {
        Promise.all([
          this.$store.dispatch('getCache', { type: 'depts' }),
          this.$store.dispatch('getCache', { type: 'agents' })
        ]).then(([depts, agents]) => {
          let optionData = []
          dealDept(depts, optionData, '')
          dealAgent(agents, optionData[0].children)
          let noDeptAgents = agents.filter(agent => agent.status === 'enable' && !agent.deptId).map(agent => ({ _id: agent._id, count: 0, type: 'agent', label: `${agent.displayName} ${agent.exten}`, pinyin: agent.pinyin }))
          optionData[0].children.push(...noDeptAgents)
          this.setDeptAgentCount(optionData[0])
          console.log(optionData)
          this.optionData = optionData
//          this.$on('resetAgent', () => {
//            this.resetAgent()
//          })
//          this.$on('deleteAgent', (_id) => {
//            this.deleteAgent(_id)
//          })
//          if (this.agentCheckedIds.length > 0) {
//            this.setCheckedAgent(this.agentCheckedIds)
//          }
        })
      },
      filterExten (agents) {
        let result = []
        let hash = {}
        agents.forEach(function (ele) {
          if (!hash[ele._id]) {
            result.push(ele)
            hash[ele._id] = true
          }
        })
        return result
      },
      handleData1 () {
        Promise.all([
          this.$store.dispatch('getCache', { type: 'depts' }),
          this.$store.dispatch('getCache', { type: 'agents' })
        ]).then(([depts, agents1]) => {
          let agents = []
          // 处理公式范围内部门里面的所有座席 存入agents
          this.objSeat.showScope.ownerdep.forEach((item) => {
            agents1.forEach((item1) => {
              if (item === item1.deptId) {
                agents.push(item1)
              }
            })
          })
          // 处理公式范围内的座席 存入agents
//          this.objSeat.showScope.user.forEach((item) => {
//            agents1.forEach(item1 => {
//              if (item === item1._id) {
//                agents.push(item1)
//              }
//            })
//          })
          this.agents = this.$store.getters.agents || {}
          this.objSeat.showScope.user.forEach((item) => {
            let agent = this.agents[item]
            if (agent) {
              agents.push(agent)
            }
          })
          // 过滤掉公式范围内重复的座席
          agents = this.filterExten(agents)
          let optionData = []
          // 处理部门 部门id不能为空
          dealDept(depts, optionData, '')
          // 处理座席
          dealAgent(agents, optionData[0].children)
          let noDeptAgents = agents.filter(agent => agent.status === 'enable' && !agent.deptId).map(agent => ({ _id: agent._id, type: 'agent', label: `${agent.displayName} ${agent.exten}`, pinyin: agent.pinyin }))
          optionData[0].children.push(...noDeptAgents)
          // 计算座席总数
          this.setDeptAgentCount(optionData[0])
          fliterDept(optionData[0])
          this.optionData = optionData
//          this.$on('resetAgent', () => {
//            this.resetAgent()
//          })
//          this.$on('deleteAgent', (_id) => {
//            this.deleteAgent(_id)
//          })
          this.$on('resetAgent', this.resetAgent1)
          this.$on('deleteAgent', this.deleteAgent1)
//          if (this.agentCheckedIds.length > 0) {
//            this.setCheckedAgent(this.agentCheckedIds)
//          }
        })
      }
    },
    beforeDestroy: function () {
      this.$off('resetAgent', this.resetAgent1)
      this.$off('deleteAgent', this.deleteAgent1)
    },
    beforeMount () {
      this.objSeat = deepClone(this.readSeat)
      this.objSeat.showScope.ownerdep ? this.objSeat.showScope.ownerdep = this.objSeat.showScope.ownerdep.split(',') : this.objSeat.showScope.ownerdep = []
      this.objSeat.showScope.user ? this.objSeat.showScope.user = this.objSeat.showScope.user.split(',') : this.objSeat.showScope.user = []
      if (this.objSeat.showScope.ownercom === 'all') {
        this.handleData()
      } else {
        this.handleData1()
      }
    }
  }
  function dealDept (depts, arr, key) {
    for (let i = 0; i < depts.length; i++) {
      let dept = depts[i]
      if (dept.pId === key) {
        let obj = {
          _id: dept._id,
          type: 'dept',
          label: dept.name,
          order: dept.order,
          children: []
        }
        arr.push(obj)
        dealDept(depts, obj.children, dept._id)
      }
    }
  }
  function dealAgent (agents, arr) {
    if (!arr) {
      return
    }
    for (let i = 0; i < arr.length; i++) {
      dealAgent(agents, arr[i].children)
      let deptAgents = agents.filter(agent => agent.status === 'enable' && agent.deptId === arr[i]._id)
      deptAgents = deptAgents.map(agent => ({ _id: agent._id, type: 'agent', label: `${agent.displayName} ${agent.exten}`, pinyin: agent.pinyin }))
      arr[i].children.push(...deptAgents)
    }
  }
  function fliterDept (optionData) {
    if (optionData.type === 'dept') {
      let i = optionData.children.length - 1
      while (i >= 0) {
        if (optionData.children[i].type === 'dept' && (optionData.children[i].count === 0)) {
          optionData.children.splice(i, 1)
        } else if (optionData.children[i].type === 'dept' && (optionData.children[i].count !== 0)) {
          fliterDept(optionData.children[i])
        }
        i--
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .el-checkbox
    padding-right 0
  .a-tree
    max-height 300px
    min-width 190px
    overflow-y auto
  .el-tree1
    border none
  .prompt
    color $c-prompt
    margin-top 10px
    padding-left 10px
</style>
